package com.redsea.rsadmin.common.aspects;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.redsea.rsadmin.common.SourceHandler;
import com.redsea.rsadmin.common.annotation.DataSource;

@Aspect
@Component 
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Order(1)
public class DataSourceAspect {
	private final Logger logger = Logger.getLogger(DataSourceAspect.class);

	@Pointcut("execution (* com.redsea.rsadmin.service.*.*(..))")
	public void anyMethod() {
	}

	static {
		System.setProperty("druid.logType", "log4j2");
	}

	/**
	 * 配置前置通知,使用在方法aspect()上注册的切入
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Before("anyMethod()")
	public void before(JoinPoint point) {
		Object target=point.getTarget();
		Class targetClass=target.getClass();
        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
		Method targetMethod=null;
		try {
			targetMethod=targetClass.getMethod(point.getSignature().getName(), parameterTypes);
			DataSource annotation = targetMethod.getDeclaredAnnotation(DataSource.class);
			if(annotation==null) {
				logger.debug("==============使用写数据源===================");
				SourceHandler.setKey("write");
			}else {
				logger.debug("==============使用"+annotation.sourceType()+"数据源===================");
				SourceHandler.setKey(annotation.sourceType());
			}
		} catch (Exception e) {
			logger.warn("获取注解失败",e);
			SourceHandler.setKey("write");
		}
	}

	@After("anyMethod()")
	public void after(JoinPoint point) {
		SourceHandler.clear();
	}
}